<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'tenant_id',
        'name',
        'service_type',
        'start_time',
        'end_time',
        'settlement_cycle',
        'min_fee',
        'max_fee',
        'billing_unit',
        'gender_requirement',
        'education_requirement',
        'min_age',
        'max_age',
        'work_location',
        'work_time',
        'work_content',
        'work_compensation',
        'work_benefits',
        'status',
        'qr_code_url',
    ];

    protected $casts = [
        'id' => 'string',
        'tenant_id' => 'string',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'min_fee' => 'decimal:2',
        'max_fee' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function getStartTimeAttribute($value): ?string
    {
        if (!$value) {
            return null;
        }

        return \Illuminate\Support\Carbon::parse($value)->timezone(config('app.timezone'))->format('Y-m-d');
    }

    public function getEndTimeAttribute($value): ?string
    {
        if (!$value) {
            return null;
        }

        return \Illuminate\Support\Carbon::parse($value)->timezone(config('app.timezone'))->format('Y-m-d');
    }

    public function getIdAttribute($value): string
    {
        return (string) $value;
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = static::generateSnowflakeId();
            }
        });
    }

    public static function generateSnowflakeId(): string
    {
        $timestamp = (int) (microtime(true) * 1000);
        $machineId = mt_rand(0, 1023);
        $sequence = mt_rand(0, 4095);

        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;

        return (string) $snowflakeId;
    }

    /**
     * 所属租户
     */
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 任务报名记录
     */
    public function applications()
    {
        return $this->hasMany(TaskApplication::class);
    }

    /**
     * 结算记录
     */
    public function settlements()
    {
        return $this->hasMany(Settlement::class);
    }

    /**
     * 已报名的自由职业者
     */
    public function freelancers()
    {
        return $this->belongsToMany(Freelancer::class, 'task_applications')
                    ->withPivot(['status', 'application_note', 'rejection_reason', 'applied_at', 'processed_at', 'processed_by'])
                    ->withTimestamps();
    }

    /**
     * 生成二维码URL
     */
    public function generateQrCode()
    {
        // 生成任务报名页面的URL
        $url = config('app.url') . '/freelancer/apply/' . $this->id;
        // 这里可以集成二维码生成库
        return $url;
    }
}
